﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using OF.Component.BLL;
using OF.Component.Model;
using OF.Utility;

namespace OF.Component.Base
{
    public class UserInfoManager
    {
        private const string LOGIN_MEMBER_PREFIX = "MEMBER_";
        

        #region 属性
        /// <summary>
        /// appID,应用ID,1:商家站点，2：顾问站点，用以决定登录页的Url
        /// </summary>
        public static int AppID
        {
            get
            {
                return EConvert.ToInt(WebConfigurationManager.AppSettings["AppID"]);
            }
        }
        /// <summary>
        /// 当前管理员ID
        /// </summary>
        public static int CurMemberID
        {
            get
            {
                HttpContext context = SiteUtility.CurContext;
                if (context != null
                    && context.User != null
                    && context.User.Identity != null
                    && context.User.Identity.IsAuthenticated
                    && context.User.Identity.Name.StartsWith(LOGIN_MEMBER_PREFIX)
                    && context.User.Identity.Name.Length > LOGIN_MEMBER_PREFIX.Length)
                {
                    try
                    {
                        return Convert.ToInt32(context.User.Identity.Name.Substring(LOGIN_MEMBER_PREFIX.Length));
                    }
                    catch
                    {

                    }
                }

                return -1;
            }
        }

        /// <summary>
        /// 当前管理员实体
        /// </summary>
        public static UserInforInfo CurMemberInfo
        {
            get
            {
                if (CurMemberID > 0)
                {
                    return UserInforOperate.GetByID(CurMemberID);
                }
                return null;
            }
        }

        /// <summary>
        /// 当前是否已经登陆
        /// </summary>
        public static bool IsLogin
        {
            get
            {
                if (CurMemberID > 0)
                {
                    return true;
                }
                return false;
            }
        }

        #endregion


        #region 方法
        public static void Login(int userID)
        {
            Login(userID, true);
        }

        /// <summary>
        /// 登陆用户
        /// </summary>
        public static void Login(int userID, bool isAutoLogin)
        {
            HttpContext context = SiteUtility.CurContext;
            string defaultUrl = "";
            //if (context.User.Identity.IsAuthenticated)
            //{
            //    if (CurMemberID == userID)
            //    {
            //        return;
            //    }
            //    FormsAuthentication.SignOut();
            //}
            var info = UserInforOperate.GetByID(userID);
            if (info == null)
            {
                return;
            }
            info.LastLoginIP = SiteInfo.GetIP();
            info.LastLoginTime = DateTime.Now;
            UserInforOperate.Update(info);

            var userName = LOGIN_MEMBER_PREFIX + userID;
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, userName, DateTime.Now, DateTime.Now.AddDays(7), true, "", "/");
            //加密序列化验证票为字符串
            string HashTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);
            UserCookie.Expires = ticket.Expiration;
            UserCookie.HttpOnly = true;
            UserCookie.Path = FormsAuthentication.FormsCookiePath;
            UserCookie.Secure = FormsAuthentication.RequireSSL;
            if (FormsAuthentication.CookieDomain != null)
            {
                UserCookie.Domain = FormsAuthentication.CookieDomain;
            }
            if (ticket.IsPersistent)
            {
                UserCookie.Expires = ticket.Expiration;
            }
            //生成Cookie
            context.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            context.Response.Cookies.Add(UserCookie);
            //跳转Url
            //HttpContext.Current.Response.Redirect(FormsAuthentication.GetRedirectUrl(userName,true));
            var returnUrl = FormsAuthentication.GetRedirectUrl(userName, true);

            if (returnUrl == "/")
            {
                if (AppID == 1) //商家首页
                {
                    defaultUrl = SiteUtility.GetBaseURL() + "/Index.aspx";
                }
                else if (AppID == 2) //顾问首页
                {
                    defaultUrl = SiteUtility.GetBaseURL() + "/counselor/counselorOrderList.aspx";
                }
            }
            else
            {
                defaultUrl = returnUrl;
            }

            context.Response.Redirect(defaultUrl, true); ;
        }

        /// <summary>
        /// 登录
        /// </summary>
        public static void Login(int userID, int days, int hours, int minustes, int seconds)
        {
            HttpContext context = HttpContext.Current;

            if (context.User.Identity.IsAuthenticated)
            {
                if (CurMemberID == userID)
                {
                    return;
                }
                FormsAuthentication.SignOut();
            }
            HttpCookie cookie = FormsAuthentication.GetAuthCookie(LOGIN_MEMBER_PREFIX + userID.ToString(), true);
            cookie.Expires = DateTime.Now + new TimeSpan(days, hours, minustes, seconds);
            context.Response.Cookies.Add(cookie);
            FormsAuthentication.SetAuthCookie(LOGIN_MEMBER_PREFIX + userID.ToString(), true);

        }

        /// <summary>
        /// 注销
        /// </summary>
        public static void LogOut()
        {
            FormsAuthentication.SignOut();
        }


        /// <summary>
        /// 必须登陆
        /// </summary>
        public static void MustLogin()
        {
            if (!IsLogin)
            {
                string appLoginUrl = "";
                if (AppID == 1)
                {
                    appLoginUrl = "/Login.aspx";
                }
                else if (AppID == 2)
                {
                    appLoginUrl = "/counselor/counselorLogin.aspx";
                }
                string loginUrl = string.Format(SiteUtility.GetBaseURL() + "{0}?returnUrl=" + HttpContext.Current.Request.Url.OriginalString, appLoginUrl);
                SiteUtility.CurHttpResponse.Write("<script>top.location.href='" + loginUrl + "';</script>");
                SiteUtility.CurHttpResponse.End();
            }

        }
        #region 个人端用户认证、权限管理
        /// <summary>
        /// 个人用户是否已经登录
        /// </summary>
        /// <returns></returns>
        public static bool IsUserLogin()
        {
            return IsLogin && CurMemberInfo.UserType == 3;
        }
        /// <summary>
        /// 个人端用户必须登录方能下单
        /// </summary>
        public static void UserMustLogin()
        {
            //|| CurMemberInfo.UserType!=3
            if (!IsLogin)
            {
                string appLoginUrl = "/customer-v1.0/login.aspx";
                string szLoginUrlFormat = "{0}{1}?returnUrl={2}";
                string loginUrl = string.Format(szLoginUrlFormat, SiteUtility.GetBaseURL(), appLoginUrl,
                    HttpContext.Current.Request.Url.OriginalString);
                //string loginUrl = string.Format(SiteUtility.GetBaseURL() + "{0}?returnUrl=" + HttpContext.Current.Request.Url.OriginalString, appLoginUrl);
                SiteUtility.CurHttpResponse.Write("<script>top.location.href='" + loginUrl + "';</script>");
                SiteUtility.CurHttpResponse.End();
            }
            else
            {
               var uri = HttpContext.Current.Request.Url;
                string defaultUrl = uri.PathAndQuery;
                //订单确认页里需要特殊处理
                if (defaultUrl.Contains("order-confirm.aspx") && !defaultUrl.Contains("uid"))
                {
                    if (!string.IsNullOrEmpty(uri.Query))
                    {
                        defaultUrl += "&uid=" + CurMemberID;
                    }
                    else
                    {
                        defaultUrl += "?uid=" + CurMemberID;
                    }
                    HttpContext.Current.Response.Redirect(defaultUrl, false);
                }

            }
           
        }

        /// <summary>
        /// 个人端用户登录方法,设置认证cookie，并返回 “返回地址”
        /// </summary>
        public static string UserLogin(int userID, bool isAutoLogin)
        {
            HttpContext context = SiteUtility.CurContext;
            string defaultUrl = "";
           
            var info = UserInforOperate.GetByID(userID);
            info.LastLoginIP = SiteInfo.GetIP();
            info.LastLoginTime = DateTime.Now;
            UserInforOperate.Update(info);

            var userName = LOGIN_MEMBER_PREFIX + userID;
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, userName, DateTime.Now, DateTime.Now.AddDays(7), true, "", "/");
            //加密序列化验证票为字符串
            string HashTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);
            UserCookie.Expires = ticket.Expiration;
            UserCookie.HttpOnly = true;
            UserCookie.Path = FormsAuthentication.FormsCookiePath;
            UserCookie.Secure = FormsAuthentication.RequireSSL;
            if (FormsAuthentication.CookieDomain != null)
            {
                UserCookie.Domain = FormsAuthentication.CookieDomain;
            }
            if (ticket.IsPersistent)
            {
                UserCookie.Expires = ticket.Expiration;
            }
            //生成Cookie
            context.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            context.Response.Cookies.Add(UserCookie);
            //跳转Url
            var returnUrl = "/";
            var referUrl = context.Request.UrlReferrer;
            if (referUrl != null)
            {
                var query = referUrl.Query;
                if (query.Contains("?returnUrl="))
                {
                    returnUrl = query.Replace("?returnUrl=", "");
                }
            }
            if (returnUrl == "/")
            {
                defaultUrl = SiteUtility.GetBaseURL();
            }
            else
            {
                defaultUrl = returnUrl;
            }

            //如果是订单确认页需要单独处理
            if (defaultUrl.Contains("order-confirm.aspx"))
            {
                var defaultUri=new Uri(defaultUrl);
                if (!string.IsNullOrEmpty(defaultUri.Query))
                {
                    defaultUrl += "&uid=" + info.UserID;
                }
                else
                {
                    defaultUrl += "?uid="+info.UserID;
                }
            }
            return defaultUrl;
            
        }

        /// <summary>
        /// 个人端用户Ajax登录方法,设置认证cookie
        /// </summary>
        public static void UserAjaxLogin(int userID, bool isAutoLogin)
        {
            HttpContext context = SiteUtility.CurContext;
            string defaultUrl = "";

            var info = UserInforOperate.GetByID(userID);
            info.LastLoginIP = SiteInfo.GetIP();
            info.LastLoginTime = DateTime.Now;
            UserInforOperate.Update(info);

            var userName = LOGIN_MEMBER_PREFIX + userID;
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, userName, DateTime.Now, DateTime.Now.AddDays(7), true, "", "/");
            //加密序列化验证票为字符串
            string HashTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);
            UserCookie.Expires = ticket.Expiration;
            UserCookie.HttpOnly = true;
            UserCookie.Path = FormsAuthentication.FormsCookiePath;
            UserCookie.Secure = FormsAuthentication.RequireSSL;
            if (FormsAuthentication.CookieDomain != null)
            {
                UserCookie.Domain = FormsAuthentication.CookieDomain;
            }
            if (ticket.IsPersistent)
            {
                UserCookie.Expires = ticket.Expiration;
            }
            //生成Cookie
            context.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            context.Response.Cookies.Add(UserCookie);
        }
        #endregion



        #endregion
    }
}
